package com.replication.jdbc.connection;

import com.replication.constants.ReplicationConstants;
import com.replication.log.Logger;

import java.sql.Connection;
import java.sql.SQLException;

public abstract class AbstructConnectionSelector implements ConnectionSelector {
    private static Logger logger = Logger.getLogger(AbstructConnectionSelector.class);

    public AbstructConnectionSelector() {
    }

    public Connection select(ReplicationConnectionProxy replicationConn, String sql) throws SQLException {
        Connection result;

        // 如果使用Master注解，则使用主库
        if(sql != null && sql.startsWith(ReplicationConstants.MASTER_HINT)) {
            result = replicationConn.getMasterConnection();
        } else {
            // 写操作用主库
            if(this.isMasterOnly(sql)) {
                result = replicationConn.getMasterConnection();
            } else {
                // 其它操作用从库
                result = replicationConn.nextSlaverConnection();
            }
        }

        logger.debug("{selector url}[" + result.getMetaData().getURL() + "]," + sql);
        return result;
    }

    protected abstract boolean isMasterOnly(String sql);

    protected static boolean existWords(String searchIn, String searchFor) {
        return searchIn.indexOf(searchFor) >= 0;
    }

    protected static boolean isSelectFrom(String sql) {
        String upperSql = sql.trim().toUpperCase();
        return existWords(upperSql, "SELECT ") && existWords(upperSql, " FROM ") && upperSql.startsWith("SELECT");
    }
}